//
//  HRReportViewController.m
//  Hear
//
//  Created by mac on 2017/9/21.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRReportViewController.h"
#import "PlaceholderTextView.h"
#import "OSSImageUploader.h"
#import "HRUserViewModel.h"
@interface HRReportViewController ()<LQPhotoPickerViewDelegate,UITextViewDelegate>
{
    //备注文本View高度
    float noteTextHeight;
    
    float pickerViewHeight;
    float allViewHeight;
}
@property (nonatomic, strong)UIScrollView *scrollView;
@property(nonatomic,strong) UIView *noteTextBackgroudView;
//备注
@property(nonatomic,strong) PlaceholderTextView *noteTextView;

//文字个数提示label
@property(nonatomic,strong) UILabel *textNumberLabel;

//文字说明
@property(nonatomic,strong) UILabel *explainLabel;

@property(nonatomic, strong)UIButton *submitBtn;
@property(nonatomic, strong)UIView *reportContentView;
@property(nonatomic, strong)HRUserViewModel *userViewModel;

@end

@implementation HRReportViewController
#pragma mark - Get and Set
- (HRUserViewModel *)userViewModel{
    if (_userViewModel == nil) {
        _userViewModel = [[HRUserViewModel alloc] init];
    }
    return _userViewModel;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"举报";
    
    self.view.backgroundColor = [UIColor whiteColor];

    
//    UIButton *leftButton = [UIButton buttonWithType:0];
//    leftButton.size = CGSizeMake(20, 20);
//    [leftButton setImage:[UIImage imageNamed:@"Back-Arrow"] forState:0];
//    [leftButton addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
//    self.navigationItem.leftBarButtonItem = leftItem;
    
    
    UIButton *submitBtn = [[UIButton alloc]init];
    submitBtn.size = CGSizeMake(40, 30);
    [submitBtn setTitle:@"提交" forState:UIControlStateNormal];
    [submitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [submitBtn addTarget:self action:@selector(submitBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:submitBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    self.submitBtn = submitBtn;

    
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped)];
    [self.view addGestureRecognizer:tapGr];
    
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:self.scrollView];
    
    self.LQPhotoPicker_superView = _scrollView;
    
    self.LQPhotoPicker_imgMaxCount = 6;
    
    [self LQPhotoPicker_initPickerView];
    
    self.LQPhotoPicker_delegate = self;
    
    [self initViews];
}


- (void)initViews{
    
    _noteTextBackgroudView = [[UIView alloc]init];
    _noteTextBackgroudView.backgroundColor = [UIColor colorWithWhite:1 alpha:1];
    
    _noteTextView = [[PlaceholderTextView alloc]init];
    _noteTextView.textColor = TEXTCOLOR;
    _noteTextView.delegate = self;
    _noteTextView.font = CustomUIFont(14);
    _noteTextView.placeholder = @"请输入举报原因";
    
    
    _textNumberLabel = [[UILabel alloc]init];
    _textNumberLabel.textAlignment = NSTextAlignmentRight;
    _textNumberLabel.font = [UIFont boldSystemFontOfSize:12];
    _textNumberLabel.textColor = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1.0];
    _textNumberLabel.backgroundColor = [UIColor whiteColor];
    _textNumberLabel.text = @"4/50    ";
    
    
    _explainLabel = [[UILabel alloc]init];
    _explainLabel.text = @"请上传至少一张说明对方违规的证据截图";
    _explainLabel.textColor = FirstTextColor;
    _explainLabel.font = [UIFont boldSystemFontOfSize:12];
    
    
    UIView *reportContentView = [UIView new];
    NSArray *textArr = @[@"诈骗或托",@"色情低俗",@"恶意骚扰，不文明语音"];
    CGFloat leftPading = 15;
    CGFloat buttonWidth = (kFullWidth-leftPading*4)/4;
    for (int i =0; i < textArr.count; i ++) {
        UIButton *button = [UIButton buttonWithType:0];
        [button setTitle:textArr[i] forState:0];
        [button setTitleColor:FirstTextColor forState:0];
        button.titleLabel.font = CustomUIFont(13);
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [reportContentView addSubview:button];
        button.layer.borderColor = FirstTextColor.CGColor;
        button.layer.borderWidth = 1;
        button.layer.cornerRadius = 5;
        button.clipsToBounds = YES;
        if (i == textArr.count-1){
            button.frame = CGRectMake(i*(buttonWidth+leftPading)+leftPading, 0, buttonWidth*2, 35);
        }else{
            button.frame = CGRectMake(i*(buttonWidth+leftPading)+leftPading, 0, buttonWidth, 35);
        }
    }
    
    [_scrollView addSubview:(self.reportContentView=reportContentView)];
    [_scrollView addSubview:_noteTextBackgroudView];
    [_scrollView addSubview:_noteTextView];
    [_scrollView addSubview:_textNumberLabel];
    
    //    [_scrollView addSubview:(self.permissionButton = permissionButton)];
    [_scrollView addSubview:_explainLabel];
    //    [_scrollView addSubview:_submitBtn];
    
    [self updateViewsFrame];
}


- (void)buttonClick:(UIButton *)button{
    self.noteTextView.text = button.titleLabel.text;
}

- (void)updateViewsFrame{
    
    if (!allViewHeight) {
        allViewHeight = 0;
    }
    if (!noteTextHeight) {
        noteTextHeight = 100;
    }
    
    _noteTextBackgroudView.frame = CGRectMake(0, 0, kFullWidth, noteTextHeight);
    
    _reportContentView.frame = CGRectMake(0, _noteTextBackgroudView.bottom+10, kFullWidth, 35);
    
    _explainLabel.frame = CGRectMake(15, _reportContentView.bottom+10, kFullWidth-30, 20);

    
    //文本编辑框
    _noteTextView.frame = CGRectMake(15, 0, kFullWidth - 30, noteTextHeight);
    
    
    //文字个数提示Label
    _textNumberLabel.frame = CGRectMake(0, _noteTextView.frame.origin.y + _noteTextView.frame.size.height-15, kFullWidth-10, 15);
    
    [self LQPhotoPicker_updatePickerViewFrameY:_explainLabel.bottom];
    

    allViewHeight = noteTextHeight + [self LQPhotoPicker_getPickerViewFrame].size.height + 30 + 100;
    
    _scrollView.contentSize = self.scrollView.contentSize = CGSizeMake(0,allViewHeight+30);
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    _textNumberLabel.text = [NSString stringWithFormat:@"%lu/50    ",(unsigned long)_noteTextView.text.length];
    if (_noteTextView.text.length > 500) {
        _textNumberLabel.textColor = [UIColor redColor];
    }
    else{
        _textNumberLabel.textColor = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1.0];
    }
    
    [self textChanged];
    
    //    if ([text isEqualToString:@"\n"]) {
    //        [textView resignFirstResponder];
    //    }
    return YES;
}

- (void)textViewDidChangeSelection:(UITextView *)textView{
    _textNumberLabel.text = [NSString stringWithFormat:@"%lu/50    ",(unsigned long)_noteTextView.text.length];
    if (_noteTextView.text.length > 50) {
        _textNumberLabel.textColor = [UIColor redColor];
    }
    else{
        _textNumberLabel.textColor = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1.0];
    }
    [self textChanged];
}

-(void)textChanged{
    
    CGRect orgRect = self.noteTextView.frame;//获取原始UITextView的frame
    
    CGSize size = [self.noteTextView sizeThatFits:CGSizeMake(self.noteTextView.frame.size.width, MAXFLOAT)];
    
    orgRect.size.height=size.height+10;//获取自适应文本内容高度
    
    if (orgRect.size.height > 100) {
        noteTextHeight = orgRect.size.height;
    }
    [self updateViewsFrame];
}

- (void)submitBtnClicked{
    
    _submitBtn.enabled = NO;
    
    if (self.noteTextView.text.length > 50){
        [MBProgressHUD showMessage:@"文字描述不超过50长度" finishBlock:nil];
        _submitBtn.enabled = YES;
        return;
    }
    if (!self.noteTextView.text.length){
        [MBProgressHUD showMessage:@"举报不能为空" finishBlock:nil];
        _submitBtn.enabled = YES;
        return;
    }
    if (!self.LQPhotoPicker_selectedAssetArray.count){
        [MBProgressHUD showMessage:@"请上传违规凭证截图" finishBlock:nil];
        _submitBtn.enabled = YES;
        return;
    }
    
    if (self.LQPhotoPicker_selectedAssetArray.count){
        // 有图片先上传图片
        [OSSImageUploader asyncUploadImages:self.LQPhotoPicker_selectedAssetArray complete:^(NSArray<NSString *> *names, UploadImageState state) {
            _submitBtn.enabled = YES;
            
            
            if (state == UploadImageFailed) return ;
            
            NSMutableArray *formatImageArr = [NSMutableArray array];
            for (NSString *url in names)
            {
                [formatImageArr addObject:[NSString stringWithFormat:@"http://%@.%@%@",BucketName,AliYunHost,url]];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                NSError *error = nil;
                NSString *imageJson = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:formatImageArr options:NSJSONWritingPrettyPrinted error:&error] encoding:NSUTF8StringEncoding];
                
                
                [self saveUserReportImageJson:imageJson];
            });
        }];
        return;
    }
    
    
    [self saveUserReportImageJson:@""];
    _submitBtn.enabled = YES;
    
}

- (void)saveUserReportImageJson:(NSString *)imageJson{
    NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
    paramDict[@"CurrentUserLocalId"] = USERID;
    paramDict[@"ReportUserLocalId"] = self.ReportUserLocalId;
    paramDict[@"ReportType"] = @"6";
    paramDict[@"OtherContent"] = self.noteTextView.text;
    paramDict[@"ReportProof"] = imageJson;
    paramDict[@"CreateTime"] = [self getCurrentTime];
    paramDict[@"ReportStatus"] = @"1";
    [self.userViewModel postSaveUserReport:paramDict isSeccess:^(BOOL isSeccess) {
        if (isSeccess){
            [MBProgressHUD showMessage:@"谢谢，Hearer已经收到你的举报了" finishBlock:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}


- (NSString *)getCurrentTime
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    
    return [formatter stringFromDate:[NSDate date]];
}

- (void)backClick{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewTapped{
    [self.view endEditing:YES];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.hidesBottomBarWhenPushed = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
